<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-calendar"></i> 药品采购
                </el-breadcrumb-item>
                <el-breadcrumb-item>采购登记</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="form-box">
                <el-form ref="formRef" :rules="rules" :model="billBase" label-width="80px">
                    <el-form-item label="供应商" prop="supplierId">
                        <el-select v-model="billBase.supplierId" placeholder="请选择供应商">
                            <el-option v-for="item in suppliers" :key="item.supplierId" :label="item.supplierName" :value="item.supplierId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="采购人员" prop="doctorId">
                        <el-select v-model="billBase.doctorId" placeholder="请选择采购人员">
                            <el-option v-for="item in doctors" :key="item.doctorId" :label="item.doctorName" :value="item.doctorId"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="药品详情" v-show="detailVisible">
                        <el-table :data="billDetailList" :key="updateKey" style="width: 100%" border>
                            <el-table-column prop="medicineName" label="药品" width="180" />
                            <el-table-column prop="quantity" label="数量" width="180" />
                            <el-table-column prop="price" label="单价" width="180" />
                        </el-table>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" icon="el-icon-plus" @click="medicineVisible = true" size="mini" round></el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">采购登记</el-button>
                        <el-button @click="onReset">清空表单</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <!-- 添加药品弹出框 -->
        <el-dialog title="添加药品" v-model="medicineVisible" width="50%">
            <el-form ref="medicineFormRef" :rules="medicineRules" :model="billDetail" label-width="80px">
                <el-form-item label="药品" prop="medicineId">
                    <el-select v-model="billDetail.medicineId" placeholder="请选择药品">
                        <el-option v-for="item in medicines" :key="item.medicineId" :label="item.medicineName" :value="item.medicineId"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="数量" prop="quantity">
                    <el-input v-model="billDetail.quantity"></el-input>
                </el-form-item>
                <el-form-item label="单价" prop="price">
                    <el-input v-model="billDetail.price" type="number"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onMedicineSubmit">添加药品</el-button>
                    <el-button @click="onMedicineReset">清空表单</el-button>
                    <el-button type="primary" @click="medicineVisible = false">关 闭</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { inject, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { addBill, allMedicine, allDoctor, allSupplier } from "../../api";
export default {
    name: "billForm",
    setup() {
        const rules = {
            doctorId: [
                { required: true, message: "请选择采购人员", trigger: "blur" },
            ],
            supplierId: [
                { required: true, message: "请选择供应商", trigger: "blur" },
            ]
        };
        const medicineRules = {
            medicineId: [
                { required: true, message: "请选择药品", trigger: "blur" },
            ],
            quantity: [
                { required: true, message: "请输入药品数量", trigger: "blur" },
            ],
            price: [
                { required: true, message: "请输入药品单价", trigger: "blur" },
            ]
        };
        const formRef = ref(null);
        const medicineFormRef = ref(null);
        // updateKey用于解决数据更新而table视图不更新的问题
        const updateKey = ref(0);

        // 表单数据
        let form = {};
        let billDetailList = [];
        let billBase = reactive({
            supplierId: null,
            doctorId: null,
        });
        let billDetail = reactive({
            medicineId: null,
            medicineName: '',
            quantity: null,
            price: null
        });

        // 添加药品
        const medicineVisible = ref(false);
        const detailVisible = ref(false);
        // 提交
        const onMedicineSubmit = () => {
            // 表单校验
            medicineFormRef.value.validate((valid) => {
                if (valid) {
                    let temp = medicines.value.find((item) => {
                        return item.medicineId === billDetail.medicineId
                    });
                    let index = billDetailList.findIndex((item) => {
                        return item.medicineId === billDetail.medicineId;
                    });
                    if (index !== -1) {
                        billDetailList[index] = {
                            medicineId: billDetail.medicineId,
                            medicineName: temp.medicineName,
                            price: billDetail.price,
                            medicineIntro: temp.medicineIntro,
                            quantity: billDetail.quantity
                        }
                    } else {
                        billDetailList.push({
                            medicineId: billDetail.medicineId,
                            medicineName: temp.medicineName,
                            price: billDetail.price,
                            medicineIntro: temp.medicineIntro,
                            quantity: billDetail.quantity
                        });
                    }
                    updateKey.value += 1;
                    medicineVisible.value = false;
                    detailVisible.value = true;
                    onMedicineReset();
                    ElMessage.success('添加成功');
                } else {
                    return false;
                }
            });
        };
        // 重置
        const onMedicineReset = () => {
            medicineFormRef.value.resetFields();
        };

        // 重置
        const onReset = () => {
            formRef.value.resetFields();
            medicineFormRef.value.resetFields();
            detailVisible.value = false;
            billDetailList.splice(0, billDetailList.length);
        };

        // 提交
        const onSubmit = () => {
            // 表单校验
            formRef.value.validate((valid) => {
                if (valid) {
                    if (billDetailList.length === 0) {
                        ElMessage.error('请添加采购药品详情信息');
                    } else {
                        form = {
                            doctorId: billBase.doctorId,
                            supplierId: billBase.supplierId,
                            billIntros: billDetailList
                        };
                        addBill(form).then(res => {
                            if (res.code === 200) {
                                onReset();
                                ElMessage.success('添加成功');
                            } else {
                                console.log("[添加采购信息] 失败: " + res.message);
                                ElMessage.error('服务器繁忙，请稍后重试');
                            }
                        })
                    }
                } else {
                    return false;
                }
            });
        };

        // 获取下拉框数据
        const medicines = ref([]);
        const doctors = ref([]);
        const suppliers = ref([]);
        const initSelectData = () => {
            allMedicine().then(res => {
                if (res.code === 200) {
                    medicines.value = res.data.medicineList
                }
            });
            allDoctor().then(res => {
                if (res.code === 200) {
                    doctors.value = res.data.doctorList;
                }
            });
            allSupplier().then(res => {
                if (res.code === 200) {
                    suppliers.value = res.data.supplierList;
                }
            })
        };
        initSelectData();

        return {
            rules,
            medicineRules,
            formRef,
            medicineFormRef,
            billBase,
            billDetail,
            form,
            medicineVisible,
            detailVisible,
            billDetailList,
            medicines,
            doctors,
            suppliers,
            updateKey,
            initSelectData,
            onSubmit,
            onReset,
            onMedicineSubmit,
            onMedicineReset
        };
    },
};
</script>